<template>
	<div class="visitor-record" :class="!hadRole ? '' : 'visitor-no-role'">
		<nav-header></nav-header>

        <div class="no-role" v-if="hadRole">
            您暂未分配该宿舍楼权限，请联系超级管理员开通~
        </div>
        <div class="zh-table" v-else>
            <div class="zh-table-open clear">
                <div class="zh-open-left fl">
                    <div class="open-width" style="width: 130px">
                        <el-select v-model="listParam.dormId" @change="changeDorm" filterable placeholder="请选择宿舍楼">
                            <el-option
                                v-for="item in dormData"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id">
                            </el-option>
                        </el-select>
                    </div>
                    <div class="open-width" style="width: 250px">
                        <el-date-picker
                            v-model="listParam.pickerTime"
                            type="daterange"
                            value-format="yyyy-MM-dd"
                            range-separator=" - "
                            start-placeholder="开始登记日期"
                            end-placeholder="结束登记日期">
                        </el-date-picker>
                    </div>
                    <div class="open-width" style="width: 175px">
                        <el-input v-model="listParam.keyword" placeholder="输入搜索内容" @keyup.enter.native="searchFunc"></el-input>
                    </div>
                    <el-button type="primary" @click="searchFunc">搜索</el-button>
                    <el-button type="primary" @click="resetList">重置</el-button>
                </div>
                <div class="zh-open-right fr">
                    <el-button type="primary" @click="newRecord('add')">添加记录</el-button>
                </div>
            </div>

            <div class="zh-table-visitor">
                <el-row :gutter="20" v-if="listData.length > 0">
                    <template  v-for="(item, inx) in listData">
                        <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="6" :key="inx">
                            <div class="item-list" @click="goToDetail(item.id)">
                                <div class="item-point">
                                    <span @click.stop.prevent="() => false">...</span>
                                    <div @click.stop.prevent="() => false">
                                        <span @click="newRecord(item)">修改</span>
                                        <span @click="deleteRow(item)">删除</span>
                                    </div>
                                </div>
                                <div class="item-title">{{item.name}}</div>
                                <div class="item-box">
                                    <div>
                                        <span><img src="./../../../../static/image/life/dormitory/building.png" />{{item.building_name}}</span>
                                        <span><i class="el-icon-time"></i>{{getTime(item.start_time)}} 至 {{getTime(item.end_time)}}</span>
                                    </div>
                                    <div>
                                        <span v-if="item.picture_status == 1">图片</span>
                                        <span v-if="item.text_status == 1">文字</span>
                                    </div>
                                </div>
                                <div class="item-footer">
                                    <span><img :src="BASE_URL + '/static/default/user_preview-1.png'">{{item.user_name}}</span>
                                    <span>{{getDateDiff(item.create_time)}}</span>
                                </div>
                            </div>
                        </el-col>
                    </template>
                </el-row>
                <template v-else>
                    <div class="no-data">
                        暂无数据
                    </div>
                </template>
            </div>

            <div class="table-pagination" v-show="totalNumber > 12">
                <el-pagination
                    @size-change="setCurrentSize"
                    @current-change="setCurrentPage"
                    :current-page="listParam.pageIndex"
                    :page-sizes="[ 12, 24, 36, 48, 120]"
                    :page-size="listParam.pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="totalNumber">
                </el-pagination>
            </div>
        </div>

        <el-dialog 
            :title="recordTitle" 
            :visible.sync="recordVisible" 
            class="add-record-manage" 
            width="550px" 
            :before-close="cancelForm"
            :close-on-click-modal="false">
            <el-form :model="recordForm" :rules="rules" ref="recordForm" label-width="100px" class="demo-record-form">
                <el-form-item label="记录时间：" required>
                    <el-col :span="11">
                        <el-form-item prop="pickerDateS">
                            <el-date-picker
                                v-model="recordForm.pickerDateS"
                                value-format="yyyy-MM-dd"
                                type="date"
                                placeholder="选择日期"
                                style="width: 100%;">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col class="line" :span="2" style="text-align: center">-</el-col>
                    <el-col :span="11">
                        <el-form-item prop="pickerDateE">
                            <el-date-picker
                                v-model="recordForm.pickerDateE"
                                value-format="yyyy-MM-dd"
                                type="date"
                                placeholder="选择日期"
                                style="width: 100%;">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-form-item>
                <el-form-item label="标题：" prop="title">
                    <el-input v-model="recordForm.title" placeholder="标题限制为16个字" maxLength="16"></el-input>
                </el-form-item>
                <el-form-item label="录入方式：" prop="mode">
                    <el-checkbox-group v-model="recordForm.mode">
                        <el-checkbox label="图片录入" name="type"></el-checkbox>
                        <el-checkbox label="文字录入" name="type"></el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
            </el-form>
            
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="cancelForm" plain>取消</el-button>
                <el-button type="primary" @click="submitRecord('recordForm')">确定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
export default {
    data() {
        return {
            hadRole: true,
            recordVisible: false, // 是否弹窗
            totalNumber: 0, // 列表总数
            recordId: null,
            recordTitle: '添加记录', // 弹窗标题
            listData: [], // 访客记录列表
            dormData: [], // 宿舍楼列表
            loading: { // loading 状态
                status: false,
                txt: '获取数据...'
            },
            listParam: { // 访客记录列表搜索条件
                keyword: '', // 关键字搜索
                dormId: '', // 宿舍楼 id
                pickerTime: [], // 开始时间和结束时间
                pageIndex: 1, // 分页当前页数
                pageSize: 12 // 每页数据数量
            },
            recordForm: {
                pickerDateS: '',
                pickerDateE: '',
                title: '',
                mode: ['图片录入', '文字录入']
            },
            rules: {
                pickerDateS: [
                    { required: true, validator: this.validatorStart, trigger: 'change' }
                ],
                pickerDateE: [
                    { required: true, validator: this.validatorEnd, trigger: 'change' }
                ],
                title: [
                    { required: true, message: '请输入标题', trigger: 'blur' },
                    { min: 1, max: 16, message: '长度在 1 到 16 个字符', trigger: 'blur' }
                ],
                mode: [
                    { type: 'array', required: true, message: '请至少选择一个录入方式', trigger: 'change' }
                ]
            }
        }
    },
    created() {
        this.getUserRole();
    },
    computed: {
        getTime() {
            return (time) => {
                return time ? time.substr(0, 10) : '';
            }
        },
    },
    methods: {
        /**
         * 根据用户角色权限获取宿舍楼
         */
        getUserRole() {
            let success = (res => {
                if (!is_empty(res.data)) {
                    this.dormData = res.data;
                    this.hadRole = false;
                    this.listParam.dormId = res.data[0].id;

                    this.getList();
                } else {
                    if (this.$g.role_id.includes(1) || this.$g.role_id.includes(2)) {
                        this.hadRole = false;
                    } else {
                        this.hadRole = true;
                    }
                }
            })

            this.$ajax.get('api/dormitory/getdormitoryBuildingByUser',{params: {user_id: this.$g.user_id}, func:{success: success}});
        },
        /**
         * 获取访客记录列表
         */
        getList() {
            this.loading.status = true;

            let success = (res => {
                this.loading.status = false;
                this.listData = res.data.data;
                this.totalNumber = res.data.data_sum;
            })

            let params = {
                building_id: this.listParam.dormId,
                start_time: this.listParam.pickerTime[0],
                end_time: this.listParam.pickerTime[1],
                keyword: this.listParam.keyword,
                page_index: this.listParam.pageIndex,
                page_size: this.listParam.pageSize
            }

            this.$ajax.get('api/dormitory/dormitoryVisitor', {params: params, func:{success: success}});
        },
        /**
         * 搜索列表
         */
        searchFunc() {
            this.listParam.pageIndex = 1;
            this.getList();
        },
        /**
         * 重置访客列表
         */
        resetList() {
            this.listParam = {
                keyword: '', 
                dormId: this.dormData[0].id, 
                pickerTime: [],
                pageIndex: 1, 
                pageSize: 12 
            }

            this.getList();
        },
        /**
         * 切换宿舍楼
         */
        changeDorm(val) {
            this.listParam = {
                keyword: '',
                dormId: val,
                pickerTime: [],
                pageIndex: 1, 
                pageSize: 12 
            }

            this.getList();
        },
        /**
         * 删除记录
         * @param {Number} obj 记录信息
         */
        deleteRow(obj) {
            let yes = (res => {
                this.loading.status = true;

                let success = (res => {
                    this.$message.success(res.msg);
                    
                    if (this.listData.length - 1 === 0) {
                        if (this.listParam.pageIndex > 1) {
                            this.listParam.pageIndex-- ;
                        } else {
                            this.listParam.pageIndex = 1;
                        }
                    }

                    this.getList();
                });
                let fail = (res =>{
                    this.$message.error(res.msg);
                    this.getList();
                })

                this.$ajax.delete('api/dormitory/dormitoryVisitor', {params: {id: obj.id}, func: {success: success, fail: fail}});
            })
            let cancel = (res => {})

            this.e_confirm({yes: yes, cancel: cancel, txt: `是否删除${obj.name}记录？`});
        },
        /**
         * 验证开始时间规则
         */
        validatorStart(rule, value, callback) {
            if (value === '') {
                callback(new Error('请选择开始时间'));
            } else {
                if (this.recordForm.pickerDateE && this.recordForm.pickerDateS >= this.recordForm.pickerDateE) {
                    callback(new Error('开始时间不能大于结束时间'));
                } else {
                    callback();
                }
            }
        },
        /**
         * 验证结束时间规则
         */
        validatorEnd(rule, value, callback) {
            if (value === '') {
                callback(new Error('请选择结束时间'));
            } else {
                if (this.recordForm.pickerDateS && this.recordForm.pickerDateS >= this.recordForm.pickerDateE) {
                    callback(new Error('结束时间不能小于开始时间'));
                } else {
                    callback();
                }
            }
        },
        /**
         * 添加/编辑 记录
         * @param {String/Number} val 添加标识/记录 id
         */
        newRecord(val) {
            this.recordVisible = true;

            if (val === 'add') {
                this.recordId = null;
                this.recordTitle = '添加记录';
                this.recordForm = {
                    pickerDateS: '',
                    pickerDateE: '',
                    title: '',
                    mode: ['图片录入', '文字录入']
                }
            } else {
                let temp = [];
                this.recordTitle = '编辑记录';
                this.recordId = val.id;

                if (val.text_status == 1) {
                    temp.push('文字录入');
                }
                if (val.picture_status == 1) {
                    temp.push('图片录入');
                }

                this.recordForm = {
                    pickerDateS: val.start_time,
                    pickerDateE: val.end_time,
                    title: val.name,
                    mode: temp
                }
            }

            this.$nextTick(() => {
                this.$refs.recordForm.clearValidate();
            })
        },
        /**
         * 保存宿舍楼信息
         * @param {String} formName 表单标识
         */
        submitRecord(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    let params = {
                        id: this.recordId,
                        name: this.recordForm.title,
                        building_id: this.recordId ? null : this.listParam.dormId,
                        start_time: this.recordForm.pickerDateS,
                        end_time: this.recordForm.pickerDateE,
                        create_id: this.recordId ? null : this.$g.user_id,
                        picture_status: this.recordForm.mode.includes('图片录入') ? 1 : 0,
                        text_status: this.recordForm.mode.includes('文字录入') ? 1 : 0
                    }
                    this.loading.status = true;

                    const success = (res => {
                        this.recordVisible = false;

                        this.getList();
                    })

                    if (this.recordId) {
                        this.$ajax.put("api/dormitory/dormitoryVisitor", params, {func: {success: success}});
                    } else {
                        this.$ajax.post("api/dormitory/dormitoryVisitor", params, {func: {success: success}});
                    }
                } else {
                    return false;
                }
            });
        },
        /**
         * 取消弹窗
         */
        cancelForm() {
            this.recordVisible = false;
        },
        /**
         * 跳到详情页
         * @param {Number} id 记录 id
         */
        goToDetail(id) {
            this.$router.push(`/life/dormitory/visitor-detail/${id}`);
        },
        /**
         * 设置列表每页数据数量
         */
        setCurrentSize(val) {
            this.listParam.pageIndex = 1;
            this.listParam.pageSize = val;

            this.getList();
        },
        /**
         * 设置列表的当前页数
         * @param {Number} val 页数
         */
        setCurrentPage(val) {
            this.listParam.pageIndex = val;

            this.getList();
        },
        /**
         * 返回创建时间离现在时间的长度
         * @param {Number} dateStr 时间戳
         */
        getDateDiff (dateStr) {
            var publishTime = Date.parse(dateStr.replace(/-/gi,"/")) / 1000,
                Dseconds,
                Dminutes,
                Dhours,
                Ddays,
                timeNow = parseInt(new Date().getTime()/1000),
                d,

                date = new Date(publishTime*1000),
                Y = date.getFullYear(),
                M = date.getMonth() + 1,
                D = date.getDate(),
                H = date.getHours(),
                m = date.getMinutes(),
                s = date.getSeconds();
                //小于10的在前面补0
                if (M < 10) {
                    M = '0' + M;
                }
                if (D < 10) {
                    D = '0' + D;
                }
                if (H < 10) {
                    H = '0' + H;
                }
                if (m < 10) {
                    m = '0' + m;
                }
                if (s < 10) {
                    s = '0' + s;
                }

            d = timeNow - publishTime;
            Ddays = parseInt(d/86400);
            Dhours = parseInt(d/3600);
            Dminutes = parseInt(d/60);
            Dseconds = parseInt(d);

            if(Ddays > 0 && Ddays < 3){
                    return M + '-' + D + ' ' + H + ':' + m;
            }else if(Ddays <= 0 && Dhours > 0){
                return '昨天'+ ' ' + H + ':' + m;
            }else if(Dhours <= 0 && Dminutes > 0){
                    return H + ':' + m;
            }else if (Dseconds < 60) {
                return '刚刚';
            }else if (Ddays >= 3 && Ddays < 30){
                return M + '-' + D + ' ' + H + ':' + m;
            }else if (Ddays >= 30) {
                return M + '-' + D + ' ' + H + ':' + m;
            }
        }
    },
}
</script>

<style lang="scss">
    .visitor-no-role {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 100%;

        .no-role {
            font-size: 20px;
        }
    }

    .visitor-record {
        .open-width {
			.el-date-editor {
				width: 100%;
				vertical-align: middle;
			}
		}

        .no-data {
            text-align: center;
            font-size: 20px;
            color: #000;
            margin-top: 100px;
        }

        .zh-table-visitor {
            margin: 40px 0;

            .item-list {
                margin-bottom: 21px;
                padding: 7px 20px 17px;
                min-height: 200px;
                background-size: cover;
                background-repeat: no-repeat;
                background-image: url('./../../../../static/image/life/dormitory/visitor-gb.png');
                box-sizing: border-box;

                .item-point {
                    position: relative;
                    margin-bottom: 25px;
                    text-align: right;
                    font-size: 25px;
                    color: #999;
                    line-height: 0;
                    letter-spacing: 1px;
                    cursor: pointer;

                    >span {
                        padding: 0 0 20px 15px;
                    }

                    div:before {
                        content: '';
                        display: block;
                        position: absolute;
                        top: -3px;
                        right: 15px;
                        width: 10px;
                        height: 10px;
                        background: #fff;
                        transform: rotate(45deg);
                        box-shadow: 0 2px 4px 0 rgba(238,220,214,0.50);
                    }

                    div {
                        position: absolute;
                        right: 0;
                        top: 20px;
                        padding: 10px 0;
                        font-size: 12px;
                        width: 74px;
                        height: 63px;
                        line-height: 23px;
                        background: #FFFFFF;
                        box-shadow: 0 2px 4px 0 rgba(238,220,214,0.50);
                        box-sizing: border-box;
                        transform: scale(0);
                        transform-origin: 100% 0%;
                        visibility: hidden;
                        transition: all 0.3s linear;

                        span {
                            display: block;
                            font-size: 12px;
                            text-align: center;
                        }

                        span:hover {
                            background: #CFE9FF;
                        }

                        span:first-child {
                            color: #333;
                        }

                        span:last-child {
                            color: #CC3445;
                        }
                    }
                }

                .item-point:hover {
                    div {
                        transform: scale(1);
                        visibility: visible;
                    }
                }

                .item-title {
                    margin-bottom: 12px;
                    font-size: 19px;
                    text-overflow: ellipsis;
                    white-space: nowrap;
                    overflow: hidden;
                }

                .item-box {
                    display: flex;
                    justify-content: space-between;
                    align-items: center;

                    >div:first-child {
                        span {
                            display: block;
                        }

                        >span:first-child {
                            margin-bottom: 12px;
                            font-size: 14px;
                            color: #B57933;

                            img {
                                margin-right: 10px;
                                vertical-align: middle;
                            }
                        }

                        >span:last-child {
                            font-size: 12px;
                            color: #666666;

                            i {
                                margin-right: 10px;
                            }
                        }
                    }

                    >div:last-child {
                        span {
                            padding: 4px 10px;
                            color: #FFFFFF;
                            background: #6885CD;
                            border-radius: 14px;
                        }
                    }
                }

                .item-footer {
                    display: flex;
                    align-items: center;
                    justify-content: space-between;
                    margin-top: 23px;
                    color: #333;

                    img {
                        margin-right: 10px;
                        width: 40px;
                        height: 40px;
                        background: #fff;
                        vertical-align: middle;
                        border-radius: 50%;
                        object-fit: cover;
                    }

                    >span:last-child {
                        color: #333;
                        font-size: 12px;
                    }
                }
            }

            .item-list:hover {
                cursor: pointer;
            }
        }
    }
</style>
